<template>
  <el-dialog
    :title="`${projectName} - 成绩排名`"
    v-model="dialogVisible"
    width="1000px"
    :before-close="handleClose"
    class="score-ranking-dialog">

    <div v-loading="loading" class="ranking-content">
      <!-- 项目信息 -->
      <el-card class="project-info-card" shadow="hover">
        <div class="project-info">
          <div class="project-name">{{ projectName }}</div>
          <div class="project-stats">
            <el-statistic title="参赛人数" :value="statistics.totalParticipants"></el-statistic>
            <el-statistic title="完成比赛" :value="statistics.completedParticipants"></el-statistic>
            <el-statistic title="平均成绩" :value="statistics.averageScore" :precision="2"></el-statistic>
          </div>
        </div>
      </el-card>

      <!-- 轮次选择 -->
      <div class="round-selector">
        <el-radio-group v-model="selectedRound" @change="handleRoundChange" size="medium">
          <el-radio-button
            v-for="round in roundOptions"
            :key="round.value"
            :label="round.value">
            {{ round.label }}
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 排名表格 -->
      <el-card class="ranking-table-card" shadow="hover">
        <template #header>
          <div class="table-header">
            <span class="header-title">
              <i class="el-icon-trophy"></i> 排名列表
            </span>
            <div class="header-actions">
              <el-button type="success" size="small" @click="handleExportRanking">
                <i class="el-icon-download"></i> 导出排名
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="rankingData"
          stripe
          border
          style="width: 100%"
          :default-sort="{ prop: 'ranking', order: 'ascending' }"
          empty-text="暂无排名数据">
          <el-table-column prop="ranking" label="排名" width="80" align="center" sortable>
            <template #default="scope">
              <div v-if="scope.row.ranking <= 3" class="medal-icon" :class="getMedalClass(scope.row.ranking)">
                <i v-if="scope.row.ranking === 1" class="el-icon-medal"></i>
                <i v-else-if="scope.row.ranking === 2" class="el-icon-medal-1"></i>
                <i v-else-if="scope.row.ranking === 3" class="el-icon-medal-2"></i>
              </div>
              <span v-else class="ranking-number">{{ scope.row.ranking }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="student.realName" label="学生姓名" width="120" align="center">
            <template #default="scope">
              <el-link type="primary" @click="handleStudentClick(scope.row.student)">
                {{ scope.row.student.realName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="student.studentNumber" label="学号" width="120" align="center"></el-table-column>
          <el-table-column prop="student.department" label="学院" width="150" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="student.className" label="班级" width="120" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="scoreValue" label="成绩值" width="120" align="center" sortable>
            <template #default="scope">
              <span class="score-value" :class="getScoreClass(scope.row)">
                {{ formatScore(scope.row.scoreValue) }} {{ scope.row.unit }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="scope">
              <el-button-group size="mini">
                <el-button
                  type="primary"
                  icon="el-icon-view"
                  @click="handleViewDetail(scope.row)"
                  title="查看详情">
                </el-button>
                <el-button
                  type="success"
                  icon="el-icon-medal"
                  @click="handleAwardMedal(scope.row)"
                  title="颁发奖牌"
                  :disabled="scope.row.ranking > 3">
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控制 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </el-card>

      <!-- 前三名展示 -->
      <el-card v-if="topThree.length > 0" class="top-three-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="header-title">
              <i class="el-icon-trophy"></i> 颁奖台
            </span>
          </div>
        </template>

        <div class="podium">
          <div class="podium-item silver" v-if="topThree[1]">
            <div class="podium-rank">2</div>
            <div class="podium-name">{{ topThree[1].student.realName }}</div>
            <div class="podium-score">{{ formatScore(topThree[1].scoreValue) }} {{ topThree[1].unit }}</div>
            <div class="podium-class">{{ topThree[1].student.className }}</div>
          </div>
          <div class="podium-item gold" v-if="topThree[0]">
            <div class="podium-rank">1</div>
            <div class="podium-name">{{ topThree[0].student.realName }}</div>
            <div class="podium-score">{{ formatScore(topThree[0].scoreValue) }} {{ topThree[0].unit }}</div>
            <div class="podium-class">{{ topThree[0].student.className }}</div>
          </div>
          <div class="podium-item bronze" v-if="topThree[2]">
            <div class="podium-rank">3</div>
            <div class="podium-name">{{ topThree[2].student.realName }}</div>
            <div class="podium-score">{{ formatScore(topThree[2].scoreValue) }} {{ topThree[2].unit }}</div>
            <div class="podium-class">{{ topThree[2].student.className }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handlePublishRanking">
          发布排名
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getScoreRanking } from '@/api/score'

export default {
  name: 'ScoreRankingDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    projectId: {
      type: [Number, String],
      default: null
    },
    projectName: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'close', 'view-detail', 'award-medal'],
  data() {
    return {
      loading: false,
      selectedRound: 1,
      roundOptions: [
        { value: 1, label: '第1轮' },
        { value: 2, label: '第2轮' },
        { value: 3, label: '第3轮' },
        { value: 4, label: '决赛' }
      ],
      rankingData: [],
      statistics: {
        totalParticipants: 0,
        completedParticipants: 0,
        averageScore: 0
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      }
    },
    topThree() {
      return this.rankingData.slice(0, 3)
    }
  },
  watch: {
    projectId: {
      handler(newVal) {
        if (newVal) {
          this.loadRankingData()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 加载排名数据
    async loadRankingData() {
      if (!this.projectId) return

      this.loading = true
      try {
        const response = await getScoreRanking(this.projectId, this.selectedRound)

        if (response.code === 200) {
          this.rankingData = response.data.ranking || []
          this.statistics = {
            totalParticipants: response.data.totalParticipants || 0,
            completedParticipants: response.data.completedParticipants || 0,
            averageScore: response.data.averageScore || 0
          }
          this.pagination.total = this.rankingData.length
        } else {
          this.$message.error(response.message || '获取排名数据失败')
        }
      } catch (error) {
        console.error('获取排名数据失败:', error)
        this.$message.error('获取排名数据失败')

        // 模拟数据用于演示
        this.simulateRankingData()
      } finally {
        this.loading = false
      }
    },

    // 模拟排名数据
    simulateRankingData() {
      const mockData = [
        {
          id: 1,
          ranking: 1,
          student: {
            id: 1,
            realName: '张三',
            studentNumber: '2021001',
            department: '计算机学院',
            className: '计算机科学与技术1班'
          },
          scoreValue: 10.58,
          unit: '秒',
          status: '已公示',
          remark: '破校记录'
        },
        {
          id: 2,
          ranking: 2,
          student: {
            id: 2,
            realName: '李四',
            studentNumber: '2021002',
            department: '电子信息学院',
            className: '电子信息工程1班'
          },
          scoreValue: 10.82,
          unit: '秒',
          status: '已公示',
          remark: ''
        },
        {
          id: 3,
          ranking: 3,
          student: {
            id: 3,
            realName: '王五',
            studentNumber: '2021003',
            department: '机械工程学院',
            className: '机械设计1班'
          },
          scoreValue: 11.05,
          unit: '秒',
          status: '已公示',
          remark: ''
        }
      ]

      this.rankingData = mockData
      this.statistics = {
        totalParticipants: 25,
        completedParticipants: 23,
        averageScore: 12.35
      }
      this.pagination.total = mockData.length
    },

    // 轮次改变
    handleRoundChange(round) {
      this.selectedRound = round
      this.loadRankingData()
    },

    // 查看详情
    handleViewDetail(row) {
      this.$emit('view-detail', row)
    },

    // 颁发奖牌
    handleAwardMedal(row) {
      this.$emit('award-medal', row)
    },

    // 学生点击
    handleStudentClick(student) {
      // 可以添加学生详情查看功能
      console.log('查看学生详情:', student)
    },

    // 导出排名
    handleExportRanking() {
      this.$confirm('确定要导出排名数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 实现导出逻辑
        this.$message.success('导出成功')
      })
    },

    // 发布排名
    handlePublishRanking() {
      this.$confirm('确定要发布该项目的排名吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实现发布排名逻辑
        this.$message.success('排名发布成功')
        this.handleClose()
      })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      // 重新加载数据
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      // 重新加载数据
    },

    // 关闭对话框
    handleClose() {
      this.$emit('close')
    },

    // 获取奖牌样式类
    getMedalClass(ranking) {
      if (ranking === 1) return 'gold-medal'
      if (ranking === 2) return 'silver-medal'
      if (ranking === 3) return 'bronze-medal'
      return ''
    },

    // 获取成绩样式类
    getScoreClass(score) {
      if (score.ranking === 1) return 'gold-score'
      if (score.ranking === 2) return 'silver-score'
      if (score.ranking === 3) return 'bronze-score'
      return ''
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      const statusMap = {
        '待审核': 'warning',
        '已公示': 'success',
        '已驳回': 'danger',
        '有异议': 'info'
      }
      return statusMap[status] || 'info'
    },

    // 格式化成绩
    formatScore(value) {
      if (value === null || value === undefined) return '-'
      return typeof value === 'number' ? value.toFixed(2) : value
    }
  }
}
</script>

<style scoped>
.score-ranking-dialog {
  border-radius: 8px;
}

.ranking-content {
  max-height: 700px;
  overflow-y: auto;
}

.project-info-card {
  margin-bottom: 16px;
}

.project-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-name {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.project-stats {
  display: flex;
  gap: 40px;
}

.round-selector {
  margin-bottom: 16px;
  text-align: center;
}

.ranking-table-card {
  margin-bottom: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-weight: 500;
  font-size: 16px;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.medal-icon {
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.gold-medal {
  color: #ffd700;
  text-shadow: 0 2px 4px rgba(255, 215, 0, 0.3);
}

.silver-medal {
  color: #c0c0c0;
  text-shadow: 0 2px 4px rgba(192, 192, 192, 0.3);
}

.bronze-medal {
  color: #cd7f32;
  text-shadow: 0 2px 4px rgba(205, 127, 50, 0.3);
}

.ranking-number {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.score-value {
  font-weight: 600;
  font-size: 14px;
}

.gold-score {
  color: #ffd700;
  font-weight: bold;
}

.silver-score {
  color: #c0c0c0;
  font-weight: bold;
}

.bronze-score {
  color: #cd7f32;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.top-three-card {
  background: linear-gradient(135deg, #fffbf0, #fff9e6);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.podium {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 40px;
  padding: 40px 0;
}

.podium-item {
  text-align: center;
  padding: 20px;
  border-radius: 12px;
  min-width: 160px;
  transition: transform 0.3s ease;
}

.podium-item:hover {
  transform: translateY(-10px);
}

.podium-item.gold {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  box-shadow: 0 8px 16px rgba(255, 215, 0, 0.3);
  transform: translateY(-20px);
}

.podium-item.silver {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  box-shadow: 0 8px 16px rgba(192, 192, 192, 0.3);
  transform: translateY(-10px);
}

.podium-item.bronze {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  box-shadow: 0 8px 16px rgba(205, 127, 50, 0.3);
}

.podium-rank {
  font-size: 36px;
  font-weight: bold;
  color: white;
  margin-bottom: 12px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.podium-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.podium-score {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.podium-class {
  font-size: 14px;
  color: #606266;
}

.dialog-footer {
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 滚动条样式 */
.ranking-content::-webkit-scrollbar {
  width: 6px;
}

.ranking-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.ranking-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.ranking-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-info {
    flex-direction: column;
    gap: 16px;
  }

  .project-stats {
    flex-direction: column;
    gap: 16px;
  }

  .podium {
    flex-direction: column;
    gap: 20px;
    padding: 20px 0;
  }

  .podium-item {
    transform: none !important;
  }

  .table-header {
    flex-direction: column;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>